package com.hayabusa.interceptor;

import com.hayabusa.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 本类用来演示: 登录检测的拦截器
 *
 * @author: hayabusa
 * @date: 2021/4/12 2:08 下午
 */
@Component//spring管理的bean
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 比如:/user/del
     *
     * preHandle - 请求进入Controller层方法之前执行的...
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //false - 拦截请求,不会放行...


        //true - 不拦截,直接放行...
        //判断是否登录
        String email=request.getParameter("email");
        User u = (User) redisTemplate.opsForValue().get("user_"+email);

        if (request.getRequestURI().endsWith("/login")||
                request.getRequestURI().endsWith(".js")||
                request.getRequestURI().endsWith(".css")||
                request.getRequestURI().endsWith(".png")||
                request.getRequestURI().endsWith(".jpg")||
                request.getRequestURI().endsWith(".jpeg")||
                request.getRequestURI().endsWith(".JPG")||
                request.getRequestURI().endsWith(".GIF")||
                request.getRequestURI().endsWith(".PNG")||
                request.getRequestURI().endsWith(".gif")
        ){
            return true;
        }
        if(u==null){
            System.out.println("拦截器拦截...");
            return false;//未登录...
        }

        System.out.println("拦截器...");
        return true;//登录...
    }

    /**
     * 进入controller层方法内部但是在出来之前...
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 执行完controller层方法之后...
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}